//
//  KcPhotoView.swift
//  KcSwiftDemo
//
//  Created by 张杰 on 2017/8/23.
//  Copyright © 2017年 张杰. All rights reserved.
//  图片九宫格展示

import UIKit
import MWPhotoBrowsers_zdst

/* demo
 fileprivate lazy var photoView: KcPhotoView = {
     let photoView = KcPhotoView()
     photoView.arrayIcon = ["http://ww2.sinaimg.cn/bmiddle/904c2a35jw1emu3ec7kf8j20c10epjsn.jpg",
     "http://ww2.sinaimg.cn/bmiddle/98719e4agw1e5j49zmf21j20c80c8mxi.jpg",
     "http://ww2.sinaimg.cn/bmiddle/67307b53jw1epqq3bmwr6j20c80axmy5.jpg",
     "http://ww2.sinaimg.cn/bmiddle/9ecab84ejw1emgd5nd6eaj20c80c8q4a.jpg",
     "http://ww2.sinaimg.cn/bmiddle/642beb18gw1ep3629gfm0g206o050b2a.gif",
     "http://ww1.sinaimg.cn/bmiddle/9be2329dgw1etlyb1yu49j20c82p6qc1.jpg",
     "http://7xpu18.com1.z0.glb.clouddn.com/lvuUKXxCYA0l_V7v0yHpahe5ylJv"
     ]
     let w = KcPhotoView.getHeight((photoView.arrayIcon?.count)!)
     photoView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: w)
     return photoView
 }()
 */

public class KcPhotoView: UIView {
    
    ///MARK: 初始化方法
    public init(isNetWorkIcon: Bool = true) {
        self.isNetWorkIcon = isNetWorkIcon
        super.init(frame: .zero)
        
        backgroundColor = UIColor.white
        addSubview(collectionView)
        
//        let bundle = Bundle(for: KcPhotoView.self)
//        let url = bundle.url(forResource: "KCSelectIcon", withExtension: "bundle")
//        let k = Bundle(url: url!)
//        let image = UIImage(named: "general_btn_addphoto" )
//        let path = Bundle(for: KcPhotoView.self).resourcePath! + "/KCSelectIcon.bundle"
//        let CABundle = Bundle(path: path)
//        let image = UIImage(named: "general_btn_addphoto", in: CABundle, compatibleWith: nil)
        
//        print(image)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 图片数组
    public var arrayIcon: [String]? {
        didSet {
            collectionView.reloadData()
        }
    }
    
    ///MARK: 根据图片的个数获取高度
    static public func getHeight(_ count: Int, contentW: CGFloat = UIScreen.main.bounds.size.width) -> CGFloat {
        if count == 0 {
            return 0
        }
        let k = 3
        let itemW = (contentW - CGFloat(10 * (k - 1))) / CGFloat(k)
        let i = (count - 1) / k + 1
        return (itemW + 10) * CGFloat(i) - 10
    }
    
    //MARK: 懒加载
    fileprivate let isNetWorkIcon: Bool
    fileprivate lazy var layout: KcPhoneFlowLayout = {
        let layout = KcPhoneFlowLayout()
        return layout
    }()
    
    fileprivate lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(KcPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "KcPhotoCollectionViewCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
    }()
}

extension KcPhotoView: UICollectionViewDataSource, UICollectionViewDelegate{
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayIcon!.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = KcPhotoCollectionViewCell.cellWithCollectionView(collectionView, indexPath: indexPath)
        cell.setIcon((arrayIcon?[indexPath.row])!, isNetWork: isNetWorkIcon)
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let brower = SDPhotoBrowser()
        brower.delegate = self
        brower.sourceImagesContainerView = collectionView
        brower.imageCount = (arrayIcon?.count)!
        brower.isDelete = false
        brower.currentImageIndex = indexPath.row
        brower.show()
    }
}

extension KcPhotoView: SDPhotoBrowserDelegate {
    public func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as! KcPhotoCollectionViewCell
        
        return cell.icon.image
    }
    
    public func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        if isNetWorkIcon {
            let string = arrayIcon![index]
            var u = URL(string: string)
            if u == nil {
                u = URL(string: string.addingPercentEscapes(using: .utf8)!)
            }
            return u
        }
        return nil
    }
}

//MARK: 私有func
extension KcPhotoView {
    override public func layoutSubviews() {
        super.layoutSubviews()
        
        collectionView.frame = bounds
    }
}
